package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl payConfig;

    public String getWxPayUrl(Long orderId, Long total) {
        // 1. 准备6个请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优商城购物中心--xx商品");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", total.toString());

        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getTradeType());  // 此处指定为扫码支付

        try {
            // 2.统一下单
            Map<String, String> resp = wxPay.unifiedOrder(data);

            // 3.校验响应结果
            // 3.1.通信标识校验
            checkResultCode(resp, "return_code", "return_msg");
            // 3.2.校验业务标识
            checkResultCode(resp, "result_code", "err_code_des");
            // 3.3.校验签名
            isSignValid(resp);

            // 4.获取url
            String url = resp.get("code_url");
            if (StringUtils.isBlank(url)) {
                throw new RuntimeException("支付交易链接为空！");
            }
            log.info("统一下单成功，获取响应：{}", resp);
            return url;
        } catch (Exception e) {
            log.error("统一下单失败！原因：{}", e);
            throw new RuntimeException(e);
        }
    }

    public void isSignValid(Map<String, String> resp){
        try{
            boolean boo1 = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
            boolean boo2 = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.MD5);
            if(!boo1 && !boo2){
                throw new RuntimeException("签名无效");
            }
        }catch (Exception e){
            throw new RuntimeException("签名校验失败！", e);
        }
    }

    public void checkResultCode(Map<String, String> resp, String code, String msg) {
        if ("FAIL".equals(resp.get(code))) {
            throw new RuntimeException(resp.get(msg));
        }
    }
}
